﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using System.Web.Services;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.PersonService;
using Fly.Common.WorkFlow;
using Telerik.Web.UI;
using System.Configuration;

namespace RN.ERP.Web.CA
{
    public partial class CACorpRegInfo : BasePage
    {
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
                BindDropDown();
                InitData();
                InitCorpFlowStatus();
            }
        }
        protected void RadGridLog_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            PersonServiceClient client = new PersonServiceClient();
            string corpUserGuid = GetCorpUserGuid();
            var logsCount = client.GetUserLogCount(corpUserGuid, string.Empty, UserInfo.CurrentArea);
            var logs = JsonConvert.DeserializeObject<List<User_Log>>(client.GetUserLogList(RadGridLog.CurrentPageIndex + 1, RadGridLog.PageSize, corpUserGuid, string.Empty, UserInfo.CurrentArea));
            RadGridLog.AllowCustomPaging = true;
            RadGridLog.VirtualItemCount = logsCount;
            RadGridLog.DataSource = logs;
        }
        /// <summary>
        /// 根据用户权限、角色初始化界面显示
        /// </summary>
        private void InitPage()
        {
            ////获取企业信息，登陆账户与企业不一致
            string corpUserGuid = GetCorpUserGuid();
            //begin是否可上传图片2013-12-4
            if (ConfigurationManager.AppSettings["CanUploadPic"] != null)
            {
                string CanUploadPic = ConfigurationManager.AppSettings["CanUploadPic"].ToString();
                if (CanUploadPic != "0" && UserInfo.RoleType == "User" && corpUserGuid == UserInfo.CorpUserGuid)
                {
                    //除管理端显示上传按钮
                    hdnCanUploadPic.Value = "1";
                }
            }//end
            ////企业类型暂时不允许修改
            DDLCorpUserType.Disabled = true;
            var currentAreaCode = UserInfo.CurrentArea;
            var corpInfo = GetCompanyinfo(corpUserGuid);       
      
            OperationResult flowEditResult = new OperationResult();
            flowEditResult = JsonConvert.DeserializeObject<OperationResult>(enterpriseServiceClient.CheckCorpEditStatus(corpInfo.CorpUserGuid.ToString(), ""));
            var flowCode = GetEmbranchmentFlow(currentAreaCode);
            var currentEmbranchEditResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Edit));
            var flowPostResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Post));
            var flowAuditResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Audit));
            var flowRejectResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Reject));
            hdnCurrentEmbranchEditResult.Value = currentEmbranchEditResult.Result ? "0" : "1";
            bool notSelfCorp = true;
            if (UserInfo.RoleType == "User" && corpUserGuid == UserInfo.CorpUserGuid)
            {
                notSelfCorp = false;
            }
            if (!flowEditResult.Result || UserInfo.RoleType == "Manager")
            {
                ////不可编辑
                hdnEditModel.Value = "1";
                ucArea.Enable = false;
            }
            else
            {
                hdnEditModel.Value = "0";
                ucArea.Enable = true;
            }

            ////企业端可查看其他企业信息，对其他企业信息不能做任何操作
            if (UserInfo.RoleType == "User" && notSelfCorp)
            {
                hdnEditModel.Value = "1";
                ucArea.Enable = false;
                hdnCurrentEmbranchEditModel.Value = "0";
                hdnCurrentEmbranchEditResult.Value = "1";////管理人员操作按钮屏蔽
            }
            if (UserInfo.RoleType == "User")
            {
                tishi.Visible = true;
            }
            else
            {
                tishi.Visible = false;
            }
        }

        private void InitData()
        {
            var currentAreaCode = UserInfo.CurrentArea;
            ////获取企业信息，登陆账户与企业不一致
            string corpUserGuid = GetCorpUserGuid();
            var corpInfo = GetCompanyinfo(corpUserGuid);
            var khCorpInfo = JsonConvert.DeserializeObject<Kh_CorpTable>(enterpriseServiceClient.GetCorpSecurity(corpUserGuid, currentAreaCode));
            var embrabchMent = JsonConvert.DeserializeObject<List<Tb_Corp_Embranchment>>(enterpriseServiceClient.GetCorpEmbranchments(JsonConvert.SerializeObject(corpInfo)));
            hdnCorpUserguid.Value = corpInfo.CorpUserGuid.ToString();
            txtCorpName.Value = corpInfo.CorpName;
            txtBussinessNum.Value = corpInfo.BussinessNum;
            txtEmail.Text = corpInfo.Email;
            txtOrginazationCode.Value = corpInfo.OrginazationCode;
            txtTel.Value = corpInfo.Tel;
            ucArea.AreaCode = corpInfo.AreaCode;
            var role = GetRoleIdByClassId(corpInfo.classID.ToString());
            DDLCorpUserType.Items.FindByValue(role).Selected = true;
            DDlCorpType.Items.FindByValue(corpInfo.CorpType.ToString()).Selected = true;
        }

        private void BindDropDown()
        {
            ////企业类型
            var CorpUserType = JsonConvert.DeserializeObject<Dictionary<string, string>>(Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString());
            DDLCorpUserType.DataSource = CorpUserType;
            DDLCorpUserType.DataValueField = "Key";
            DDLCorpUserType.DataTextField = "Value";
            DDLCorpUserType.DataBind();
            DDLCorpUserType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            ////所有权性质
            var CorpType = JsonConvert.DeserializeObject<Dictionary<string, string>>(Application[ApplicationConstant.APPLICATION_CORPTYPE].ToString());
            DDlCorpType.DataSource = CorpType;
            DDlCorpType.DataValueField = "Key";
            DDlCorpType.DataTextField = "Value";
            DDlCorpType.DataBind();
            DDlCorpType.Items.Insert(0, new ListItem("--请选择--", "-1"));
        }

        public string GetAreaTitle(object areaCode)
        {
            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length >= 2)
                {
                    var areaInfos = JsonConvert.DeserializeObject<List<a_AreaInfo>>(Application[ApplicationConstant.APPLICATION_AREA].ToString());
                    var currentArea = areaInfos.Where(a => code.StartsWith(a.Code)).FirstOrDefault();
                    title = currentArea == null ? "" : currentArea.Title;
                }
            }
            return title;
        }

        public string GetSubAreaTitle(object areaCode)
        {
            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length > 2)
                {
                    var subAreaInfos = JsonConvert.DeserializeObject<List<ModelService.a_AreaSubInfo>>(basicServiceClient.GetQu(code.Substring(0, 2)));
                    var currentSubArea = subAreaInfos.Where(a => a.SortCode == areaCode).FirstOrDefault();
                    title = currentSubArea == null ? "" : currentSubArea.Title;
                }
            }
            return title;
        }

        public string GetEmbranchmentFlow(object areaCode)
        {
            string flowTitle = "";
            if (areaCode == null)
            {
                return flowTitle;
            }
            string code = areaCode.ToString();
            Tb_Corp_CompanyInfo corpInfo = new Tb_Corp_CompanyInfo();
            corpInfo.CorpUserGuid = Guid.Parse(GetCorpUserGuid());
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), code));
            if (flow != null)
            {
                flowTitle = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            return flowTitle;
        }

        private Tb_Corp_CompanyInfo GetCompanyinfo(string corpUserGuid)
        {
            QueryCompanyInfoCondition queryCompanyInfoCondition =
               new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(corpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var corpInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea));
            return corpInfo;
        }

        private string GetCorpUserGuid()
        {
            string corpUserGuid = Request.QueryString["corpUserGuid"];
            if (string.IsNullOrEmpty(corpUserGuid))
            {
                corpUserGuid = UserInfo.CorpUserGuid;
            }
            return corpUserGuid;
        }

        private string GetRoleIdByClassId(string classID)
        {
            var roleClassIds = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetDictionary("RoleClassId", "", ""));
            var curRoleClass = roleClassIds.FirstOrDefault(r => r.Value == classID);
            if (!string.IsNullOrEmpty(curRoleClass.Key))
            {
                return curRoleClass.Key;
            }
            return "";
        }

        private void InitCorpFlowStatus()
        {
            if (UserInfo.RoleType == "User")
            {
                var status = JsonConvert.DeserializeObject<List<FlowStatus>>(enterpriseServiceClient.GetCorpFlowStatus(GetCorpUserGuid(), UserInfo.CurrentArea));
                rptCorpFlowStatus.DataSource = status;
                rptCorpFlowStatus.DataBind();
            }
        }

        public override bool IsCheckPermission
        {
            get { return false; }
        }
    }
}